<template>
	<div class="detail-msg" id="detailMsg">
		<div id="editorElem" style="text-align:left;"></div>
	</div>
</template>

<script>
import E from 'wangeditor';
export default {
	name: 'DetailMsg',
	props: {
		value: {
			type: String,
			default: ''
		},
		changeInterval: {
			type: Number,
			default: 200
		}
	},
	data() {
		return {
			editor: null,
			btnLock: false
		};
	},
	mounted() {
		this.editor = new E('#editorElem');

		// setTimeout(() => {
		// 	this.editor.txt.html(this.value);
		// }, 100)
		this.editor.config.onchange = html => {
			// let text = editor.txt.text();
			// if (this.cache) localStorage.editorCache = html;
			console.log(html);
			this.$emit('input', html);
			// this.$emit('on-change', html, text)
		};
		const upload = this.$service.common.upload();
		this.editor.config.onchangeTimeout = this.changeInterval;
		this.editor.config.uploadImgHeaders = {
			Authorization: this.$store.state.user.token
		};
		this.editor.config.uploadFileName = 'file'; //上传参数 自定义
		this.editor.config.uploadImgServer = upload.url; // 上传图片
		// 监听
		this.editor.config.uploadImgHooks = {
			// before: function(xhr, editor, files) {
			// 	// 图片上传之前触发
			// },
			// success: function(xhr, editor, result) {
			// 	// 图片上传并返回结果，图片插入成功之后触发
			// },
			// fail: function(xhr, editor, result) {
			// 	console.log('插入图片失败！');
			// },
			// error: function(xhr, editor) {
			// 	console.log('插入图片失败！');
			// },
			// timeout: function(xhr, editor) {
			// 	console.log('插入图片失败！');
			// },
			customInsert: function(insertImg, result) {
				insertImg(result.data);
			}
		};
		this.editor.create();
	},
	watch: {
		value(val) {
			if (!val) {
				return;
			}
			if (!this.btnLock) {
				this.btnLock = true;
				let value = JSON.parse(this.value);
				if (value.operate === 'edit') {
					this.editor.txt.html(value.detailMsg);
				}
			}
		}
	}
};
</script>

<style lang="stylus" scoped>
.detail-msg {

}
</style>
